﻿
using System.Windows.Input;
using AnyCAD.Foundation;
using System.Windows;
using AnyCAD.NX.ViewModel;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System;
using AnyCAD.NX.Common;
using CommunityToolkit.Mvvm.Input;
using RapidUI;
using Fluent;

namespace Rapid.CAX.ViewModel
{
    public partial class RapidMainViewModel : MainRibbonViewModel
    {
        public ListBox mOutputMessage;

        public RapidMainViewModel(IRenderView renderer, ListBox outputBox)
            :base(renderer)
        {
            mOutputMessage = outputBox;

            OutputMessage("Me","Welcome to use RapidCAX!");

            var process = ProcessManager.Instance.Start("pclserver", @"PclServer.exe",
                string.Format("--hostId anycad.pcl --slaveId pcl.anycad"),
                OutputMessage);
            if(process == null)
            {
                OutputMessage("PclServer", "Failed to execute PclServer.");
            }
        }

        public override Ribbon GetRibbonBar()
        {
            return ((MainWindow)App.Current.MainWindow).mRibbon;
        }

        public void SetTitle(string title)
        {
            ((MainWindow)App.Current.MainWindow).Title = title;
        }

        void AddOutputBox(string msg)
        {
            mOutputMessage.Items.Add(msg);
        }
        public void OutputMessage(string name, string? msg)
        {
            if (msg == null)
                return;

            System.Windows.Application.Current.Dispatcher.Invoke(AddOutputBox, msg);
        }

        [RelayCommand]
        void OnQueryShape()
        {

            TopoShapeList shapeList = new TopoShapeList();

            var doc = Document;
            var table = doc.FindTable(nameof(DrawableElement));
            foreach(var id in table.GetIds())
            {
                var shapeElement = ShapeElement.Cast(doc.FindElement(id));
                if(shapeElement != null)
                {
                   var shape = shapeElement.GetFinalShape();
                   if(shape != null)
                    {
                        shapeList.Add(shape);
                    }
                }               
            }

            OutputMessage("Query", String.Format("Shape count {0}", shapeList.Count));

            //保存到STEP文件
            //if(shapeList.Count > 0)
            //{
            //    var shape = ShapeBuilder.MakeCompound(shapeList);
            //    StepIO.Save(shape, "d:/xxx.stp");
            //}
        }
    }
}
